/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package searcherPackage.Index;

import searcherPackage.services.Stemmer;
import searcherPackage.services.StopWords;

/**
 *
 * @author i_khri
 */
public class Term implements Comparable<Term>{

    public static Term newInstance(String token) throws InvalidTermException{
        Term term = new Term(token);
        if(term.termStr.isEmpty()){
            term = null;
            throw new InvalidTermException("Token " + token + " cannot be transformed to a valid token.");
        }else{
            return term;
        }
    }



    public static Term fromIndexString(String theString){
        int beginIndex = theString.indexOf('[');
        return new Term(theString.substring(0, beginIndex));
    }



    public String getTerm(){
        return termStr;
    }



    @Override
    public int hashCode() {
        int hash = 7;
        hash = 11 * hash + (this.termStr != null ? this.termStr.hashCode() : 0);
        return hash;
    }



    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Term other = (Term) obj;
        if ((this.termStr == null) ? (other.termStr != null) : !this.termStr.equals(other.termStr)) {
            return false;
        }
        return true;
    }



    @Override
    public String toString(){
        return termStr;
    }



    public int compareTo(Term o) {
        return termStr.compareTo(o.termStr);
    }



    private Term(String token){
        token = token.replaceAll("[\\s\\p{Punct}]|[\\d]*","").trim().toLowerCase();

        if(token.length()>=2 && !StopWords.contains(token)) {
            // Stemming the tokens
            Stemmer stemmer = new Stemmer();
            stemmer.add(token.toCharArray(), token.toCharArray().length);
            stemmer.stem();
            this.termStr = stemmer.toString();
        }else{
            this.termStr = "";
        }
    }


    
    private String termStr;
}
